<template>
    <div style="display: flex">
        <el-button type="primary" style="margin-right: 15px" @click="addItem">新增</el-button>
        <el-input v-model="search" placeholder="请输入档期编号"
            style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px;" clearable></el-input>
        <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;" @click="load">搜索
        </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" :row-style="{ height: '77px' }" border
        style="width: calc(100vw - 240px);margin-top: 20px;height: 75vh;color: #909399;font-size: 15px;">
        <el-table-column prop="stageNum" label="档期编号" align="center" width="150" />
        <el-table-column prop="username" label="管理人员" align="center" width="150" />
        <el-table-column prop="flow" label="档期状态" align="center" width="150">
            <template #default="scope">
                <el-tag type="success" v-if="scope.row.flow === 0">准备中</el-tag>
                <el-tag type="success" v-else-if="scope.row.flow === 1">进行中</el-tag>
                <el-tag type="success" v-else-if="scope.row.flow === 2">已结束</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" align="center" width="auto" />
        <el-table-column prop="endTime" label="结束时间" align="center" width="auto" />
        <el-table-column fixed="right" label="操作" align="center" width="200">
            <template v-slot="scope">
                <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" icon=Delete @click="deleteItem(scope.row.id)">删除</el-button>
                <br>
                <el-button type="primary" size="small" icon=document @click="viewAttachment(scope.row)">附件</el-button>
                <el-button type="primary" size="small" icon=printer @click="exportPdf(scope.row)">打印</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 10px">
        <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" :background="true"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="dialogVisible" title="档期操作" width="560" @close="reset('form')">
        <el-form label-position="top" :inline="true" :model="form" ref="form" :rules="rules">
            <el-form-item label="档期编号" prop="stageNum">
                <el-input v-model="form.stageNum" placeholder="请输入档期编号" clearable></el-input>
            </el-form-item>
            <el-form-item label="管理人员" prop="userId">
                <el-select v-model="form.userId" placeholder="请选择管理人员" style="width: 185px" filterable clearable>
                    <el-option v-for="item in userOptions" :key="item.id" :label="item.username"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
                <el-date-picker v-model="form.startTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
                    placeholder="选择开始时间" style="width: 185px">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
                <el-date-picker v-model="form.endTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
                    placeholder="选择结束时间" style="width: 185px">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="档期状态" prop="flow">
                <el-select v-model="form.flow" placeholder="请选择档期状态" style="width: 185px" clearable>
                    <el-option v-for="course in flowOptions" :key="course.value" :label="course.label"
                        :value="course.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="改进措施" autocomplete="off" style="width: 100%">
                <el-input type="textarea" v-model="form.improvMeasure" :rows="8" placeholder="请输入改进措施" clearable>
                </el-input>
            </el-form-item>
            <el-form-item label="培训心得" autocomplete="off" style="width: 100%">
                <el-input type="textarea" v-model="form.trainExperience" :rows="8" placeholder="请输入培训心得" clearable>
                </el-input>
            </el-form-item>
            <el-form-item label="附件" autocomplete="off" style="width: 100%">
                <el-upload :action="'api/files/upload'" :file-list="fileList" :before-upload="beforeUpload"
                    :on-success="attachmentUploadSuccess" :on-remove="attachmentRemove" style="width:100%" drag
                    multiple>
                    <el-icon class="el-icon--upload">
                        <upload-filled />
                    </el-icon>
                    <div class="el-upload__text">
                        拖拽或<em>点击</em>上传
                    </div>
                    <div class="el-upload__tip">
                        (请上传小于1GB的文件)
                    </div>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="reset('form')">取消</el-button>
                <el-button type="primary" @click="submitForm('form')">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="attachmentVisible" :close-on-click-modal="false" title="相关附件" width="1000px" align-center
        draggable>
        <div class="attachmentDialog">
            <div class="attachmentTitle">
                <span>附件查看</span>
            </div>
            <el-table :data="attachmentTable" :cell-style="cellStyle" highlight-current-row
                :header-cell-style="{ background: '#f4f3f9' }" class="attachmentTable"
                style="width:100%;height:calc(100% - 29px)" border>
                <el-table-column align="center" prop="fileName" label="附件名称">
                </el-table-column>
                <el-table-column align="center" label="查看">
                    <template v-slot="scope">
                        <el-button type="primary" icon="view" size="small" @click="viewFile(scope.row)">查看</el-button>
                        <el-button type="primary" icon="Download" size="small"
                            @click="downloadFile(scope.row)">下载</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </el-dialog>

    <el-dialog title="文件预览" v-model="openItemFileDialog" width="70%" top="5vh" class="custom-preview-dialog"
        @close="closeFile" v-if="openItemFileDialog">
        <div class="preview-container">
            <!-- PDF 预览 -->
            <vue-office-pdf v-if="fileExt === 'docx' || fileExt === 'doc'" :src="pdfSrc" style="height: 600px" />

            <iframe v-if="fileExt !== 'docx' && fileExt !== 'doc'" :src="pdfSrc" frameborder="0"
                style="background-color: #fff;width: 100%; height: 600px"></iframe>
        </div>
    </el-dialog>

</template>

<script>
import request from "~/utils/request.js";
import { useRouter } from "vue-router"
import { ElMessage } from "element-plus";
import VueOfficePdf from '@vue-office/pdf'


export default {
    components: {
        VueOfficePdf
    },
    data() {
        const validateEndTime = (rule, value, callback) => {
            if (!value) {
                callback('请选择结束时间');
                return;
            }

            if (this.form.startTime && new Date(value) < new Date(this.form.startTime)) {
                callback('结束时间不能早于开始时间');
            } else {
                callback();
            }
        };
        return {
            dialogVisible: false,
            attachmentVisible: false, // 相关附件弹窗
            openItemFileDialog: false, // 文件预览弹窗
            attachmentTable: [],
            fileList: [], // 专门用于el-upload的文件列表
            tableData: [],
            form: {
                attachment: []
            },
            userOptions: [],
            flowOptions: [
                {
                    value: 0,
                    label: '准备中',
                },
                {
                    value: 1,
                    label: '进行中',
                },
                {
                    value: 2,
                    label: '已结束',
                }
            ],
            search: '',
            currentPage: 1,
            pageSize: 10,
            total: 0,
            rules: {
                stageNum: [
                    { required: true, message: '请输入档期编号', trigger: 'blur' },
                ],
                userId: [
                    { required: true, message: '请选择管理人员', trigger: 'blur' },
                ],
                startTime: [
                    { required: true, message: '请选择开始时间', trigger: 'blur' },
                ],
                endTime: [
                    { required: true, message: '请选择结束时间', trigger: 'blur' },
                    { validator: validateEndTime, trigger: 'change' }
                ],
                flow: [
                    { required: true, message: '请选择档期状态', trigger: 'blur' },
                ],
            },
        }
    },
    created() {
        this.load()
        this.getUserOptions()
    },
    methods: {
        load() {
            request.get("/stage/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&stageNum=" + this.search).then(res => {
                if (res.code === '200') {
                    for (let key in res.data) {
                        if (key === "records") {
                            this.tableData = res.data[key];
                        } else if (key === "total") {
                            this.total = res.data[key];
                        }
                    }
                } else {
                    ElMessage.error("错误" + res.msg)
                }
            })
        },
        getUserOptions() {
            request.get("/user/all").then(res => {
                this.userOptions = res.data
            })
        },
        // 编辑
        editItem(item) {
            request.get("attachment/getAttachment", {
                params: {
                    correlationTable: "stage",
                    correlationId: item.id
                }
            }).then(res => {
                if (res.code === '200') {
                    this.form = {
                        ...item,
                        attachment: res.data.records,
                    };
                    // 转换附件数据为el-upload需要的格式
                    this.fileList = res.data.records.map(file => ({
                        id: file.id,
                        name: file.fileName,
                        url: file.filePath,
                    }));
                    this.dialogVisible = true
                }
            })
        },
        addItem() {
            this.dialogVisible = true;
        },
        // 删除
        deleteItem(scope) {
            this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get("/stage/delete/" + scope).then(res => {
                    if (res.code === '200') {
                        this.$message.success("成功")
                        this.load()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            });
        },
        // 提交
        submitForm(val) {
            this.$refs[val].validate((valid) => {
                if (valid) {
                    request.post("/stage/edit", this.form).then(res => {
                        if (res.code === '200') {
                            this.$message({
                                message: "成功",
                                type: "success"
                            })
                            this.load()
                            this.reset(val)
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            })
        },
        // 取消
        reset(val) {
            this.dialogVisible = false;
            this.form = {
                attachment: []
            };
            this.fileList = [];
            this.$refs[val].resetFields();
        },
        // 上传前的文件验证
        beforeUpload(file) {
            const maxSize = 1024 * 1024 * 1024;
            if (file.size > maxSize) {
                this.$message.warning('文件大小超过1GB限制!');
                return false;
            }
            return true;
        },
        // 上传文件成功
        attachmentUploadSuccess(response, file, fileList) {
            this.form.attachment.push({
                id: null,
                uid: file.uid,
                fileName: file.name,
                filePath: `/api/file/download/${response}`
            });
            this.$message.success('上传成功');
        }
        ,
        attachmentRemove(file, fileList) {
            if (!file.id) {
                // 移除对应的文件
                this.form.attachment = this.form.attachment.filter(f => f.uid !== file.uid);
                return;
            }
            request.get(`/attachment/delete/${file.id}`).then(res => {
                if (res.code != '200') {
                    return;
                }
                if (res.data.toString() == "true") {
                    this.form.attachment = this.form.attachment.filter((f) => f.id !== file.id);
                    this.$message.success('删除成功');
                } else {
                    this.$message.error('删除失败');
                }
            })
        },

        // 查看附件
        viewAttachment(row) {
            // 查看附件
            request.get("attachment/getAttachment", {
                params: {
                    correlationTable: "stage",
                    correlationId: row.id
                }
            }).then(res => {
                if (res.code === '200') {
                    this.attachmentTable = res.data.records
                }
            })
            this.attachmentVisible = true
        },
        // 关闭相关附件弹窗
        closeAttachmentDialog() {
            this.attachmentVisible = false
        },
        // 下载文件
        downloadFile(item) {
            const link = document.createElement('a');
            link.href = item.filePath;
            link.download = item.fileName || '未知文件';

            // 兼容某些浏览器
            document.body.appendChild(link);

            link.click();
            setTimeout(() => {
                document.body.removeChild(link);
            }, 0);
        },
        // 查看文件
        async viewFile(item) {
            const { filePath, fileName } = item;

            this.fileExt = fileName.split('.').pop().toLowerCase()

            try {
                if (this.fileExt !== "docx" && this.fileExt !== "doc") {
                    this.pdfSrc = filePath
                } else {
                    const previewUrl = `/api/files/preview/${encodeURIComponent(filePath.split('/').pop())}`
                    const response = await fetch(previewUrl)
                    const blob = await response.blob()

                    this.pdfSrc = URL.createObjectURL(blob)
                }
                this.openItemFileDialog = true
            } catch (error) {
                this.$message.error('文档预览失败: ' + error.message)
            }
        },
        closeFile() {
            this.openItemFileDialog = false
            // 释放URL对象
            if (this.pdfSrc && this.pdfSrc.startsWith('blob:')) {
                URL.revokeObjectURL(this.pdfSrc);
            }
            this.pdfSrc = "";

            // 销毁iframe的资源
            const iframes = document.querySelectorAll('iframe');
            iframes.forEach(iframe => {
                iframe.src = 'about:blank';
            });
        },
        handleCurrentChange(item) {
            // 改变当前页码触发
            this.currentPage = item
            this.load()
        },
        handleSizeChange(item) {   // 改变当前每页的个数触发
            this.pageSize = item
            this.load()
        },
        async exportPdf(val) {
            let router = useRouter()
            // 清空pdf数据
            if (this.$store.state.pdfData !== null && this.$store.state.pdfData !== '') {
                this.$store.commit("SET_PDFDATA", {})
            }
            // 获取pdf数据
            await this.getData(val)

            this.$router.push("/pdf")
        },
        // 时间装换为周期 "2025-05-11 09:47:43","2025-05-11 09:47:38"转换为"2025.05.11~2025.5.11"
        timeToPeriod(startTime, endTime) {
            // 替换所有的-
            let start = startTime.split(' ')[0].replaceAll('-', '.')
            let end = endTime.split(' ')[0].replaceAll('-', '.')
            let period = start + '~' + end
            return period
        },
        // 获取当前日期
        getNowDate() {
            let date = new Date()
            let year = date.getFullYear()
            let month = date.getMonth() + 1
            let day = date.getDate()
            return year + '-' + month + '-' + day
        },
        // 计算总签到率
        calculateTotalSignRate(classData) {
            let totalActualSign = 0;
            let totalRequiredSign = 0;

            // 遍历每个班级
            for (const className in classData) {
                if (classData.hasOwnProperty(className)) {
                    const courses = classData[className];

                    // 遍历每个班级的课程
                    for (const course of courses) {
                        // 避免除零错误，跳过requiredSign为0的课程
                        if (course.requiredSign > 0) {
                            totalActualSign += course.actualSign;
                            totalRequiredSign += course.requiredSign;
                        }
                    }
                }
            }

            // 计算总签到率，处理除零情况
            const totalSignRate = totalRequiredSign > 0
                ? (totalActualSign / totalRequiredSign) * 100
                : 0;

            return totalSignRate >= 100 ? 100 : totalSignRate.toFixed(2);
        },
        // 计算总合格率和平均分
        calculateTotalPassRateAndAverage(data) {
            let totalPass = 0;
            let totalCount = 0;
            let totalScore = 0;
            for (const item of data) {
                if (item.exampaperGetScore !== null) {
                    totalCount++;
                    if (item.isPass == 1) {
                        totalPass++;
                    }
                    totalScore += item.exampaperGetScore;
                }
            }
            let totalPassRate = totalCount > 0 ? ((totalPass / totalCount) * 100) : 100;
            totalPassRate = totalPassRate >= 100 ? 100 : totalPassRate;
            let avgScore = totalCount > 0 ? (totalScore / totalCount).toFixed(2) : 0;
            return { totalPassRate, avgScore };
        },
        // 处理培训计划与材料数组
        handlePlanItemsAndMaterials(items) {
            // 只保留前三个数据
            if (items.length > 3) {
                items = items.slice(0, 3);
                // 在数组追加第四个数据 "..."
                items.push("...")
            }
            return items
        },

        async getData(val) {
            let training
            await request.get("/stage/getTraining/", {

                params: {
                    id: val.id
                }
            }).then(res => {

                if (res.code === '200') {
                    training = res.data
                } else {
                    this.$message.error(res.msg)
                }
            })
            let { totalPassRate, avgScore } = this.calculateTotalPassRateAndAverage(training.topStudents)

            this.$store.commit("SET_PDFDATA", {
                title: '线上培训',
                period: val.stageNum, // 编号
                date: this.getNowDate() + '归档', // 日期
                duration: this.timeToPeriod(val.startTime, val.endTime), // 培训周期
                participants: training.participants, // 参训人数
                attendance: this.calculateTotalSignRate(training.classSignReta), // 课程总签到率
                passRate: totalPassRate, // 总合格率
                satisfaction: this.calculateTotalSignRate(training.examSignReta), // 考试总签到率
                avgScore: avgScore, // 平均分
                courseSignRate: training.classSignReta, // 班级课程签到率数据
                examSignRate: training.examSignReta, // 班级考试签到率数据
                planItems: training.planItems, // 课程
                materials: training.materials, // 课件
                teachers: training.teachers, // 培训讲师
                manages: training.manages, // 培训负责人
                certificates: {
                    periodLog: training.periodLog, // 班主任日志
                    classSum: training.classSum,  // 办班总结
                    trainSitu: training.trainSitu, // 执行情况
                },
                topStudents: training.topStudents, // 学员信息
                courseFeedbacks: training.courseFeedbacks.slice(0, 3), // 课程评价
                feedbacks: training.feedbacks.slice(0, 3), // 培训讲师评价
                xinde: val.trainExperience, // 心得
                cuoshi: val.improvMeasure, // 改进措施
            })
        }
    }
}
</script>

<style scoped>
::v-deep .custom-preview-dialog {
    /* 限制弹窗最大高度为视口的90% */
    max-height: 90vh;
    display: flex;
    flex-direction: column;
}

/* 内容容器 */
::v-deep .custom-preview-dialog .el-dialog__body {
    flex: 1;
    padding: 0 !important;
    /* 移除默认padding */
    overflow: hidden;
    /* 隐藏溢出内容 */
}

.preview-container {
    height: 100%;
    display: flex;
    flex-direction: column;
}

/* Office内容区域 */
.office-content {
    flex: 1;
    /* 填充剩余空间 */
    min-height: 400px;
    /* 最小高度保证 */
    overflow: auto;
    /* 添加滚动条 */
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    background: white;
}

.office-content {
    word-wrap: break-word;
    overflow-wrap: break-word;
}

/* 调整TXT预览样式 */
pre {
    flex: 1;
    overflow: auto;
    margin: 0;
    background: white;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}
</style>
